import { request } from '@/utils/request'
import { ref, onMounted } from 'vue'
import { defineComponent } from 'vue'
import { useRoute } from 'vue-router'

export interface NewsItem {
  id: number
  title: string
  summary: string
  image: string
  date: string
  category: string
  clicks: number
}

export async function fetchNewsList(params = {}): Promise<NewsItem[]> {
  return await request('/api/news/', 'GET', params)
}

const newsList = ref<NewsItem[]>([])

onMounted(async () => {
  newsList.value = await fetchNewsList()
})

function formatDate(dateStr: string) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

export default defineComponent({
  setup() {
    const route = useRoute()
    return { route, newsList, formatDate }
  },
  template: `
    <div class="news-list">
      <div class="news-item" v-for="news in newsList" :key="news.id">
        <div class="news-image">
          <img :src="news.image" :alt="news.title">
        </div>
        <div class="news-content">
          <h3 class="news-title">
            <router-link :to="\`/news/article/\${news.id}\`">{{ news.title }}</router-link>
          </h3>
          <p class="news-summary">{{ news.summary }}</p>
          <div class="news-meta">
            <span class="news-date">{{ formatDate(news.date) }}</span>
          </div>
        </div>
      </div>
    </div>
  `
})